package com.sddf.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sddf.common.constant.UserConstant;
import com.sddf.common.exception.Assert;
import com.sddf.common.result.enums.impl.BusinessCode;
import com.sddf.system.mapper.UserDetailMapper;
import com.sddf.system.mode.dto.UserRegisterDto;
import com.sddf.system.mode.entity.User;
import com.sddf.system.mode.entity.UserDetail;
import com.sddf.system.service.UserService;
import com.sddf.system.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.UUID;

/**
* @author 30383
* @description 针对表【u_user(用户表)】的数据库操作Service实现
* @createDate 2024-11-13 15:51:23
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    @Autowired
    private UserDetailMapper userDetailMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public void register(UserRegisterDto userRegistDto) {
        //判断手机号是否存在
        User phoneUser = this.getOne(Wrappers.lambdaQuery(User.class).eq(
                User::getPhone, userRegistDto.getPhone()
        ));
        Assert.error(phoneUser!=null,BusinessCode.PHONE_EXISTED);
        //判断用户名是否存在
        User nameUser=this.getOne(Wrappers.lambdaQuery(User.class).eq(User::getUserName,userRegistDto.getUserName()));
        Assert.error(nameUser!=null,BusinessCode.USER_EXISTED);
        //保存用户信息

        //保存用户
        User user = User.builder()
                .userName(userRegistDto.getUserName())
                .phone(userRegistDto.getPhone())
                .pwd(passwordEncoder.encode(userRegistDto.getPwd()))
                .userType(UserConstant.USER_TYPE_PERSONAL)
                .userStatus(0)
                .build();
        this.save(user);

        //保存用户详情
        UserDetail userDetail = UserDetail.builder()
                .id(user.getId())
                .userName(user.getUserName())
                .phone(user.getPhone())
                .borrowMoney(new BigDecimal("0"))
                .userCode("UC_" + UUID.randomUUID().toString().substring(0, 10))
                .cardBindStatus(1)
                .build();

        userDetailMapper.insert(userDetail);
    }
}




